package com.example.alspringaop.spring.framework.context;

import com.example.alspringaop.spring.framework.annotation.ALAutowired;
import com.example.alspringaop.spring.framework.annotation.ALController;
import com.example.alspringaop.spring.framework.annotation.ALService;
import com.example.alspringaop.spring.framework.aop.ALJdkDynamicAopProxy;
import com.example.alspringaop.spring.framework.aop.config.ALAopConfig;
import com.example.alspringaop.spring.framework.aop.support.ALAdvisedSupport;
import com.example.alspringaop.spring.framework.beans.ALBeanWrapper;
import com.example.alspringaop.spring.framework.beans.config.ALBeanDefinition;
import com.example.alspringaop.spring.framework.beans.support.ALBeanDefinitionReader;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class ALApplicationContext {

    private ALBeanDefinitionReader reader;

    private Map<String,ALBeanDefinition> beanDefinitionMap = new HashMap<>();

    private Map<String, ALBeanWrapper> factoryBeanInstanceCache = new HashMap<>();

    private Map<String,Object> factoryBeanObjectCache = new HashMap<>();


    public ALApplicationContext(String...configLocations){
        //1. 加载配置文件
        reader = new ALBeanDefinitionReader(configLocations);

        try{
            //2.解析配置文件，封装为BeanDefinition
            List<ALBeanDefinition> beanDefinitions = reader.loadBeanDefinitions();

            //3. 把BeanDefinition缓存起来
            doRegistBeanDefinition(beanDefinitions);

            doAutowrited();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doRegistBeanDefinition(List<ALBeanDefinition> beanDefinitions) throws Exception {
        for (ALBeanDefinition beanDefinition : beanDefinitions) {
            if(this.beanDefinitionMap.containsKey(beanDefinition.getFactoryBeanName())){
                throw new Exception("The " + beanDefinition.getFactoryBeanName() + "is exists");
            }
            beanDefinitionMap.put(beanDefinition.getFactoryBeanName(),beanDefinition);
            beanDefinitionMap.put(beanDefinition.getBeanClassName(),beanDefinition);
        }
    }

    private void doAutowrited(){
        //调用getBean
        //这一步，所有的Bean并没有真正的实例化，还是配置阶段
        for (Map.Entry<String,ALBeanDefinition> beanDefinitionEntry : this.beanDefinitionMap.entrySet()) {
            String beanName = beanDefinitionEntry.getKey();
            getBean(beanName);
        }
    }

    /**
     * bean的实例化，DI是从这个方法开始的
     * @param beanName
     * @return
     */
    public Object getBean(String beanName){
        //1.先拿到BeanDefinition的配置信息
        ALBeanDefinition beanDefinition =  this.beanDefinitionMap.get(beanName);

        //2.反射实例化newInstance()
        Object instance = instantiateBean(beanName,beanDefinition);

        //3.封装成一个BeanWrapper
        ALBeanWrapper beanWrapper = new ALBeanWrapper(instance);
        //4.保存到IOC容器
        factoryBeanInstanceCache.put(beanName,beanWrapper);

        //5.执行依赖注入
        populateBean(beanName,beanDefinition,beanWrapper);

        return beanWrapper.getWrapperInstance();

    }

    /**
     * 注入属性
     * @param beanName
     * @param beanDefinition
     * @param beanWrapper
     */
    private void populateBean(String beanName, ALBeanDefinition beanDefinition, ALBeanWrapper beanWrapper) {
        //可能涉及到循环依赖？
        //A{ B b}
        //B{ A b}
        //用两个缓存，循环两次
        //1、把第一次读取结果为空的BeanDefinition存到第一个缓存
        //2、等第一次循环之后，第二次循环再检查第一次的缓存，再进行赋值

        Object instance = beanWrapper.getWrapperInstance();

        Class<?> clazz = beanWrapper.getWrappedClass();

        //在Spring中@Component
        if(!(clazz.isAnnotationPresent(ALController.class) || clazz.isAnnotationPresent(ALService.class))){
            return;
        }

        //把所有的包括private/protected/default/public 修饰字段都取出来
        for (Field field : clazz.getDeclaredFields()) {
            if(!field.isAnnotationPresent(ALAutowired.class)){ continue; }

            ALAutowired autowired = field.getAnnotation(ALAutowired.class);

            //如果用户没有自定义的beanName，就默认根据类型注入
            String autowiredBeanName = autowired.value().trim();
            if("".equals(autowiredBeanName)){
                //field.getType().getName() 获取字段的类型
                autowiredBeanName = field.getType().getName();
            }

            //暴力访问
            field.setAccessible(true);

            try {
                if(this.factoryBeanInstanceCache.get(autowiredBeanName) == null){
                    continue;
                }
                //ioc.get(beanName) 相当于通过接口的全名拿到接口的实现的实例
                field.set(instance,this.factoryBeanInstanceCache.get(autowiredBeanName).getWrapperInstance());
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                continue;
            }
        }

    }

    /**
     * 创建真正的实例对象
     * @param beanName
     * @param beanDefinition
     * @return
     */
    private Object instantiateBean(String beanName, ALBeanDefinition beanDefinition){
        String className = beanDefinition.getBeanClassName();
        Object instance = null;
        try{
            if(factoryBeanObjectCache.containsKey(beanName)){
                instance = this.factoryBeanObjectCache.get(beanName);
            }else{
                Class<?> clazz = Class.forName(className);
                //2.默认的类名首字母小写
                instance = clazz.newInstance();
                //==============从AOP开始==============
                //如果满足条件，直接返回aop对象
                //1.加载aop的配置文件
                ALAdvisedSupport config = instantionAopConfig(beanDefinition);
                config.setTarget(instance);
                config.setTargetClass(clazz);

                /**
                 * 判断规则，要不要生成代理类，如果有就覆盖原生对象
                 * 如果不要，就不做任何处理，返回原生对象
                 */
                if(config.pointCutMath()){
                    instance = new ALJdkDynamicAopProxy(config).getProxy();
                }
                //==========AOP结束========
                this.factoryBeanObjectCache.put(beanName,instance);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return instance;
    }

    private ALAdvisedSupport instantionAopConfig(ALBeanDefinition beanDefinition) {
        ALAopConfig config = new ALAopConfig();
        config.setPointcut(this.reader.getConfig().getProperty("pointCut"));
        config.setAspectClass(this.reader.getConfig().getProperty("aspectClass"));
        config.setAspectBefore(this.reader.getConfig().getProperty("aspectBefore"));
        config.setAspectAfter(this.reader.getConfig().getProperty("aspectAfter"));
        config.setAspectAfterThrow(this.reader.getConfig().getProperty("aspectAfterThrow"));
        config.setAspectAfterThrowingName(this.reader.getConfig().getProperty("aspectAfterThrowingName"));
        return new ALAdvisedSupport(config);
    }


    public Object getBean(Class beanClass){
        return getBean(beanClass.getName());
    }

    public int getBeanDefinitionCount(){
        return this.beanDefinitionMap.size();
    }

    public String[] getBeanDefinitionNames() {
        return this.beanDefinitionMap.keySet().toArray(new String[this.beanDefinitionMap.size()]);
    }

    public Properties getConfig() {
        return this.reader.getConfig();
    }






}
